/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.db4o.groovy;

import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;

/**
 *
 * @author klevgert
 */
public class Db4oGroovyQueryShell extends Db4oGroovyShell {

  private String type = "java.lang.Object";
  private String constraint = "true";
  private String qualifier = "obj";

  public Db4oGroovyQueryShell() {
  }

  public Db4oGroovyQueryShell(ObjectContainer objectContainer) {
    super(objectContainer);
  }

  public Db4oGroovyQueryShell(ObjectContainer objectContainer, String type, String constraint) {
    super(objectContainer);
    this.type = type;
    this.constraint = constraint;
  }
  public Db4oGroovyQueryShell(ObjectContainer objectContainer, Class type, String constraint) {
    super(objectContainer);
    this.type = type.getName();
    this.constraint = constraint;
  }

  public Db4oGroovyQueryShell(String type, String constraint) {
    this.type = type;
    this.constraint = constraint;
  }

  public ObjectSet runNativeQuery() {
    return (ObjectSet) this.run();
  }

  @Override
  public Object run() {

    this.setScript(
            "class APredicate" +
            " extends com.db4o.query.Predicate<" + getType() + "> {\n" +
            "" +
            " public boolean match(" + getType() + " " + getQualifier() + ") " +
            " { return " + getConstraint() + "; };\n" +
            " public boolean match(Object obj) { return " + getConstraint() + "; };\n" +
            "};\n" +
            "objectContainer.query( new APredicate() );");

    ObjectSet os = (ObjectSet) super.run();
    return os;
  }

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
    this.setVariable("type", type);
  }

  public String getConstraint() {
    return constraint;
  }

  public void setConstraint(String constraint) {
    this.constraint = constraint;
  }

  public String getQualifier() {
    return qualifier;
  }

  public void setQualifier(String qualifier) {
    this.qualifier = qualifier;
  }

}
